import Axios from 'axios'
import AxiosConfig from './axios.config'

var fileUploadConfig = {
    baseURL: '',
    timeout: 50000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}

Axios.interceptors.request.use(function (config) {
    return config
}, function (error) {
    return Promise.reject(error)
})

Axios.interceptors.response.use(function (response) {
    return response
}, function (error) {
    return Promise.reject(error)
})

/**
 * Get 方法获取参数时，需拼接，
 * @param {*} parmas ;
 * GET方法传入对象，然后拼接
 */
let _getParmas = (parmas) => {
    let _parmas = ''
    for (let item in parmas) {
        _parmas += item + '=' + parmas[item] + '&'
    };
    return '?' + _parmas.substr(0, _parmas.length - 1)
}

class Ajax {
    static Post (url, parmas) {
        return new Promise((resolve, reject) => {
            Axios.post(url, parmas, AxiosConfig).then((res) => {
                resolve(Ajax.AjaxHandlerFunction(res.data, resolve, reject))
            }).catch((error) => {
                reject(new Error(error))
                // reject(new Error('Ajax ' + url + ' Error'))
            })
        })
    }
    static Get (url, parmas) {
        return new Promise((resolve, reject) => {
            Axios.get(url + _getParmas(parmas), AxiosConfig).then((res) => {
                resolve(Ajax.AjaxHandlerFunction(res.data, resolve, reject))
            }).catch((error) => {
                reject(new Error(error))
                // reject(new Error('Ajax ' + url + ' Error'))
            })
        })
    }
    static All (functionArr, callbackFN) {
        Axios.all(functionArr)
            .then(Axios.spread(function () {
                callbackFN(...arguments)
            }))
    }
    static upLoadFile (url, parmas) {
        return new Promise((resolve, reject) => {
            Axios.post(url, parmas, fileUploadConfig).then((res) => {
                resolve(Ajax.AjaxHandlerFunction(res.data, resolve, reject))
            }).catch((error) => {
                reject(new Error(error))
                // reject(new Error('Ajax ' + url + ' Error'))
            })
        })
    }
    static AjaxHandlerFunction (data, resolve, reject) {
        let _data = typeof data == 'string' ? JSON.parse(data) : data
        switch (_data.code.toString()) {
        case '100':
            // 成功返回
            let responseData = _data.data
            resolve(responseData)
            break
        case '200':
            reject(_data.desc)
            // 校验出错
            break
        case '301':
            resolve({
                errorTip: _data.desc
            })
            break
        default:
            reject(_data.desc)
            break
        }
    }

}
export default Ajax
